package com.napenalki.toto.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.napenalki.toto.dao.UserDao;
import com.napenalki.toto.domain.User;

@Transactional
@Repository
public class JpaUserDao implements UserDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public User addUser(User user) {
        entityManager.persist(user);
        return user;
    }

    @Override
    public User findUserByName(String userName) {
        return entityManager.find(User.class, userName);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> findAllUsers() {
        return entityManager.createQuery("SELECT u FROM User u")
            .getResultList();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> findUsersOrderedByPoints() {
        return entityManager.createQuery(
            "SELECT u FROM User u ORDER BY u.points DESC").getResultList();
    }

    @Override
    public User updateUser(User user) {
        User userx = findUserByName(user.getUserName());
        if (userx != null) {
            userx.setPassword(user.getPassword());
            userx.setEmail(user.getEmail());
            userx.setDisplayName(user.getDisplayName());
            userx.setPoints(user.getPoints());
            entityManager.merge(userx);
            return userx;
        } else {
            entityManager.persist(user);
            return user;
        }
    }

    @Override
    public void deleteUser(User user) {
        User userx = findUserByName(user.getUserName());
        if (userx != null) {
            entityManager.remove(userx);
        }
    }
}
